<template>
  <div class="clubs-container">
    <h2>社团管理</h2>
    
    <!-- 搜索工具栏 -->
    <div class="toolbar">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="社团名称">
          <el-input v-model="searchForm.nameFuzzy" placeholder="请输入社团名称" clearable />
        </el-form-item>
        <el-form-item label="社长姓名">
          <el-input v-model="searchForm.presidentNameFuzzy" placeholder="请输入社长姓名" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="success" @click="handleAdd">新增社团</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 社团列表 -->
    <el-table :data="clubList" border style="width: 100%" v-loading="loading">
      <el-table-column prop="name" label="社团名称" />
      <el-table-column prop="description" label="社团简介" show-overflow-tooltip />
      <el-table-column prop="creatorName" label="社长" />
      <el-table-column prop="totalMemberCount" label="成员数" width="100" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
            {{ scope.row.status === 1 ? '正常' : '已禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" :formatter="formatDateTime" />
      <el-table-column label="操作" width="280">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button 
            :type="scope.row.status === 1 ? 'warning' : 'success'" 
            size="small" 
            @click="handleToggleStatus(scope.row)"
          >
            {{ scope.row.status === 1 ? '禁用' : '启用' }}
          </el-button>
          <el-button type="info" size="small" @click="handleViewMembers(scope.row)">查看成员</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 社团表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="clubForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="社团名称" prop="name">
          <el-input v-model="clubForm.name" />
        </el-form-item>
        <el-form-item label="社团简介" prop="description">
          <el-input type="textarea" v-model="clubForm.description" rows="3" />
        </el-form-item>
        <el-form-item label="社团logo" prop="logo">
          <el-input v-model="clubForm.logo" placeholder="请输入logo图片地址" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 成员列表对话框 -->
    <el-dialog
      title="社团成员"
      v-model="memberDialogVisible"
      width="800px"
    >
      <el-table :data="memberList" border style="width: 100%">
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="realName" label="真实姓名" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="joinTime" label="加入时间" :formatter="formatDateTime" />
        <el-table-column prop="role" label="角色">
          <template #default="scope">
            <el-tag :type="scope.row.role === '社长' ? 'success' : ''">
              {{ scope.row.role === '社长' ? '社长' : '成员' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import dayjs from 'dayjs'

// 列表数据
const clubList = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 搜索表单
const searchForm = reactive({
  nameFuzzy: '',
  presidentNameFuzzy: ''
})

// 社团表单
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)
const clubForm = reactive({
  id: '',
  name: '',
  description: '',
  logo: ''
})

// 成员相关
const memberDialogVisible = ref(false)
const memberList = ref([])
const currentClubId = ref(null)

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入社团名称', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入社团简介', trigger: 'blur' }
  ]
}

// 格式化时间
const formatDateTime = (row, column) => {
  return row[column.property] ? dayjs(row[column.property]).format('YYYY-MM-DD HH:mm:ss') : ''
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  // 清理 ResizeObserver
  if (resizeObserver.value) {
    resizeObserver.value.disconnect()
    resizeObserver.value = null
  }
}

// 加载社团列表
const loadClubs = async () => {
  loading.value = true
  try {
    const params = {
      pageNo: currentPage.value,
      pageSize: pageSize.value,
      nameFuzzy: searchForm.nameFuzzy,
      presidentNameFuzzy: searchForm.presidentNameFuzzy
    }

    const res = await axios.get('/club/admin/loadDataList', { params })

    if (res.data.status === 'success') {
      clubList.value = res.data.data.list
      total.value = res.data.data.totalCount
    } else {
      ElMessage.error(res.data.info || '获取社团列表失败')
    }
  } catch (error) {
    console.error('获取社团列表失败:', error)
    ElMessage.error('获取社团列表失败')
  } finally {
    loading.value = false
  }
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  loadClubs()
}

// 页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  loadClubs()
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadClubs()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  currentPage.value = 1
  loadClubs()
}

// 新增社团
const handleAdd = () => {
  dialogTitle.value = '新增社团'
  dialogVisible.value = true
  Object.keys(clubForm).forEach(key => {
    clubForm[key] = ''
  })
}

// 处理编辑操作
const handleEdit = (row) => {
  dialogTitle.value = '编辑社团'
  dialogVisible.value = true
  Object.assign(clubForm, row)
}

// 处理表单提交
const handleSubmit = async () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let res
        if (clubForm.id) {
          // 如果有id，则是编辑操作
          res = await axios.post('/club/updateClubById', clubForm)
        } else {
          // 否则是新增操作
          res = await axios.post('/club/add', clubForm)
        }

        if (res.data.status === 'success') {
          ElMessage.success(clubForm.id ? '编辑社团成功' : '新增社团成功')
          dialogVisible.value = false
          loadClubs()
        } else {
          ElMessage.error(res.data.info || (clubForm.id ? '编辑社团失败' : '新增社团失败'))
        }
      } catch (error) {
        console.error((clubForm.id ? '编辑社团失败:' : '新增社团失败:'), error)
        ElMessage.error(clubForm.id ? '编辑社团失败' : '新增社团失败')
      }
    } else {
      console.log('表单验证失败')
      return false
    }
  })
}

// 处理状态切换
const handleToggleStatus = async (row) => {
  try {
    const isEnable = row.status === 0;  // 当前是禁用状态，需要启用
    const confirmMessage = isEnable 
      ? '确定要启用该社团吗？启用后可以在用户管理中任命社长' 
      : '确定要禁用该社团吗？禁用后该社团的社长将变为普通成员';
    
    await ElMessageBox.confirm(confirmMessage, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const res = await axios.post('/club/toggleStatus', {
      id: row.id,
      creatorId: null,  // 禁用时将移除社长身份
      status: isEnable ? 0 : 1  // 反转 status 字段的值
    });

    if (res.data.status === 'success') {
      ElMessage.success(isEnable ? '启用成功' : '禁用成功');
      loadClubs();  // 重新加载列表
    } else {
      ElMessage.error(res.data.info || '操作失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败:', error);
      ElMessage.error('操作失败');
    }
  }
}

// 处理删除操作
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该社团吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const res = await axios.post('/club/deleteClubById', { id: row.id });

    if (res.data.status === 'success') {
      ElMessage.success('删除成功');
      loadClubs();  // 重新加载列表
    } else {
      ElMessage.error(res.data.info || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
    }
  }
}

const handleViewMembers = async (row) => {
  try {
    const res = await axios.get('/club/getMembersByClubId', { params: { clubId: row.id } });
    if (res.data.status === 'success') {
      // 修改字段映射
      memberList.value = res.data.data.map(member => ({
        username: member.userName,
        realName: member.userRealName,
        email: member.email,
        joinTime: member.createdAt,
        role: member.memberRole // 确保这里使用 memberRole
      }));
      currentClubId.value = row.id;
      memberDialogVisible.value = true;
    } else {
      ElMessage.error(res.data.info || '获取成员信息失败');
    }
  } catch (error) {
    console.error('获取成员信息失败:', error);
    ElMessage.error('获取成员信息失败');
  }
}

// 添加 ResizeObserver 实例
const resizeObserver = ref(null)

onMounted(() => {
  loadClubs()

  // 示例：假设有一个元素需要观察
  const element = document.querySelector('.some-element-to-observe')
  if (element) {
    resizeObserver.value = new ResizeObserver(entries => {
      for (let entry of entries) {
        console.log('Element size changed:', entry.contentRect)
      }
    })
    resizeObserver.value.observe(element)
  }
})

// 添加卸载时的清理逻辑
onUnmounted(() => {
  if (resizeObserver.value) {
    resizeObserver.value.disconnect()
  }
})
</script>

<style scoped>
.clubs-container {
  padding: 20px;
}

.toolbar {
  margin-bottom: 20px;
  background: #fff;
  padding: 20px;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  background: #fff;
  padding: 15px;
  border-radius: 4px;
  z-index: 1;  /* 确保分页组件在最上层 */
  position: relative;
}

/* 确保分页组件内的元素可见 */
:deep(.el-pagination) {
  margin: 0;
  padding: 0;
}
</style>